package server

import (
	v1 "limiter-example/api/helloworld/v1"
	"limiter-example/internal/conf"
	"limiter-example/internal/service"
	"time"

	"github.com/go-kratos/aegis/ratelimit/bbr"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/ratelimit"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/transport/http"
)

// NewHTTPServer new an HTTP server.
func NewHTTPServer(c *conf.Server, greeter *service.GreeterService, logger log.Logger) *http.Server {
	var opts = []http.ServerOption{
		http.Middleware(
			recovery.Recovery(),
			//自定义限流器，当触发限流器时会直接拒绝当前的请求，并返回错误429码ErrLimitExceed
			ratelimit.Server(
				ratelimit.WithLimiter(bbr.NewLimiter(
					bbr.WithWindow(5*time.Second),
					bbr.WithBucket(50),
					// bbr.WithCPUQuota(800),
					bbr.WithCPUThreshold(100),
				)),
			),
		),
	}
	if c.Http.Network != "" {
		opts = append(opts, http.Network(c.Http.Network))
	}
	if c.Http.Addr != "" {
		opts = append(opts, http.Address(c.Http.Addr))
	}
	if c.Http.Timeout != nil {
		opts = append(opts, http.Timeout(c.Http.Timeout.AsDuration()))
	}
	srv := http.NewServer(opts...)
	v1.RegisterGreeterHTTPServer(srv, greeter)
	return srv
}
